package com.hmall.mq;

import com.alibaba.fastjson.JSON;
import com.hmall.common.pojo.Item;
import com.hmall.common.pojo.ItemDoc;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Slf4j
@Component
/**
 * mq消费端
 */
public class RabbitListenerConsumer {

    @Autowired
    private RestHighLevelClient client;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "hmall.ikun1"),
            exchange = @Exchange(name = "itcast.cxk", type = ExchangeTypes.DIRECT),
            key = "delete"
    ))
    /**
     * 删除文档
     */
    public void listenTopicQueue1(String id){
        // 1.准备Request
        DeleteRequest request = new DeleteRequest("hotel", id);
        // 2.发送请求
        try {
            client.delete(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            log.error("删除文档失败：id{}",id);
        }
    }

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "hmall.ikun2"),
            exchange = @Exchange(name = "itcast.cxk", type = ExchangeTypes.DIRECT),
            key = "save"
    ))
    /**
     * 全量新增文档
     */
    public void listenTopicQueue2(String json){
        // 1.根据id查询酒店数据
        Item item = JSON.parseObject(json, Item.class);
        // 2.转换为文档类型
        ItemDoc itemDoc = new ItemDoc(item);
        // 3.将ItemDoc转json
        json = JSON.toJSONString(itemDoc);
        String id = itemDoc.getId().toString();

        // 4.准备Request对象
        IndexRequest request = new IndexRequest("hotel").id(id);
        //新增前先做删除操作
        DeleteRequest requestDel = new DeleteRequest("hotel", id);

        // 5.准备Json文档
        request.source(json, XContentType.JSON);
        // 6.发送请求
        try {
            client.delete(requestDel, RequestOptions.DEFAULT);
        } catch (IOException e) {
            log.error("新增前删除失败：{}",id);
        }
        try {
            client.index(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            log.error("新增失败：{}",id);
        }
    }
}